package com.bawei.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bawei.api.RemoteMallUserService;
import com.bawei.common.core.domain.R;
import com.bawei.mall.product.domain.Index.ProductIndex;
import com.bawei.mall.product.domain.Po.*;
import com.bawei.mall.product.domain.Vo.CarVo;
import com.bawei.mall.product.domain.Vo.OrderVo;
import com.bawei.mall.product.mapper.CAddressMapper;
import com.bawei.mall.product.mapper.CCarMapper;
import com.bawei.mall.product.mapper.CProductMapper;
import com.bawei.mall.product.mapper.CReadHistoryMapper;
import com.bawei.mall.product.service.ICCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author：liurui
 * @Package：com.bawei.mall.search.service.impl
 * @Project：mall_cloud
 * @name：ShoppingCartServiceImpl
 */
@Service
public class CCarServiceImpl extends ServiceImpl<CCarMapper,Car> implements ICCarService {
    @Autowired
    private CCarMapper mapper;

    @Autowired
    private CProductMapper cProductMapper;

    @Autowired
    private CReadHistoryMapper cReadHistoryMapper;

    @Autowired
    private CAddressMapper cAddressMapper;

    @Autowired
    private RemoteMallUserService remoteMallUserService;

    @Override
    public void quantity(Integer id, Integer quantity) {
        mapper.quantity(id,quantity);
    }

    @Override
    public OrderVo generateConfirmOrder(Integer[] cartIds) {
        return getorderVo(cartIds);
    }

    @Override
    public List<CarVo> listt() {
        //先查询出购物车表的数据
        //mybits-plus
        QueryWrapper<Car> wrapper = new QueryWrapper<>();
        List<Car> list = mapper.selectList(wrapper);
        //List<Car> list=mapper.list();
        return getlistVo(list);
    }


    @Override
    public void clear() {
        //mybits-plus
        QueryWrapper<Car> wrapper = new QueryWrapper<>();
        mapper.delete(wrapper);
    }

    @Override
    public void add(Integer productId, Integer productSkuId) {
        //添加购物车
        //mybits-plus
        //mapper.insert(car);
        mapper.add(getCar(productId,productSkuId));
    }


    private OrderVo getorderVo(Integer[] cartIds) {
        OrderVo orderVo = new OrderVo();
        //给carVo赋值
        orderVo.setCartPromotionItemList(getlist(cartIds));
        //给calcAmount赋值
        orderVo.setCalcAmount(getCalcAmount(cartIds));
        //给couponHistoryDetailList赋值
        orderVo.setCouponHistoryDetailList(new ArrayList<>());
        //给integrationConsumeSetting赋值
        orderVo.setIntegrationConsumeSetting(cProductMapper.findByIntegrationConsumeSetting());
        //给memberIntegration赋值
        orderVo.setMemberIntegration(ProductIndex.SETMEMBERINTEGRATION);
        //查询登录人地址
        R<com.bawei.mall.search.domain.Po.User> r = remoteMallUserService.findUser();
        com.bawei.mall.search.domain.Po.User user = r.getData();
        List<Address> addresses = cAddressMapper.findByAddress(user.getId());
        orderVo.setMemberReceiveAddressList(addresses);
        return orderVo;
    }


    private CalcAmount getCalcAmount(Integer[] cartIds) {
        List<Car> list = mapper.findlist(cartIds);
        if (list == null || list.isEmpty()) {
            // 处理空列表的情况
            return null; // 或者返回一个带有错误信息的 CalcAmount 对象
        }
        //获取用户信息，远程调用通过redis->get(username)获取
        R<com.bawei.mall.search.domain.Po.User> r = remoteMallUserService.findUser();
        com.bawei.mall.search.domain.Po.User user = r.getData();

        //设置默认值
        BigDecimal price = BigDecimal.ZERO;
        BigDecimal promotionAmount = BigDecimal.ZERO;
        //TODO 测试数据，后续可迭代为MyBatis动态查询
        for (Car car : list) {
            SkuStockList skuStock = cReadHistoryMapper.findByCar(car.getProductSkuId());
            if (skuStock != null) {
                price = price.add(BigDecimal.valueOf(skuStock.getPrice()));
            }
        }


        // 设置会员优惠金额 0黄金会员500 1铂金会员300 2钻石会员200
        Integer memberLevelId = user.getMemberLevelId();
        if(memberLevelId==0){
            //0黄金会员80%
            promotionAmount = price.subtract(price.multiply(BigDecimal.valueOf(0.8)));
        }else if(memberLevelId==1){
            //1铂金会员90%
            promotionAmount = price.subtract(price.multiply(BigDecimal.valueOf(0.9)));
        }else if(memberLevelId==2){
            //2钻石会员95%
            promotionAmount = price.subtract(price.multiply(BigDecimal.valueOf(0.95)));
        }

        //改造成会员优惠方式
//        if (price.compareTo(BigDecimal.valueOf(1000)) >= 0 && price.compareTo(BigDecimal.valueOf(5000)) < 0) {
//            promotionAmount = BigDecimal.valueOf(100.0);
//        } else if (price.compareTo(BigDecimal.valueOf(5000)) >= 0) {
//            promotionAmount = BigDecimal.valueOf(200.0);
//        }

        BigDecimal payAmount = price.subtract(promotionAmount);
        payAmount = payAmount.max(BigDecimal.valueOf(ProductIndex.SETFREIGHTAMOUNT)); // 确保支付金额不小于运费

        CalcAmount calcAmount = new CalcAmount();
        calcAmount.setFreightAmount(BigDecimal.valueOf(ProductIndex.SETFREIGHTAMOUNT)); // 假设运费是固定的
        calcAmount.setTotalAmount(price);
        calcAmount.setPayAmount(payAmount);
        calcAmount.setPromotionAmount(promotionAmount);
        return calcAmount;
    }

    private Car getCar(Integer productId, Integer productSkuId) {
        Car car = new Car();
        //获取用户信息，远程调用通过redis->get(username)获取
        R<com.bawei.mall.search.domain.Po.User> r = remoteMallUserService.findUser();
        com.bawei.mall.search.domain.Po.User user = r.getData();
        car.setMemberId(user.getId());
        car.setMemberNickname(user.getUsername());
        car.setProductId(productId);
        car.setProductSkuId(productSkuId);
        return car;
    }

    private List<CarVo> getlistVo(List<Car> list) {
        ArrayList<CarVo> listVo = new ArrayList<>();
        //循环list集合Po转Vo->前台
        //TODO 测试数据，后续可迭代为MyBatis动态查询
        for (Car car : list) {
            //先查询相关联的表数据
            //查询product商品表的关联数据
            Product product=cProductMapper.findByCar(car.getProductId());
            //查询sku表的关联数据
            SkuStockList skuStock=cReadHistoryMapper.findByCar(car.getProductSkuId());
            //new一个carVo对象用于赋值
            CarVo carVo = new CarVo();
            //主键id
            carVo.setId(car.getId());
            //用户id
            carVo.setMemberId(car.getMemberId());
            //用户名称
            carVo.setMemberNickname(car.getMemberNickname());
            //商品表主键id
            carVo.setProductId(car.getProductId());
            //价格
            carVo.setPrice(skuStock.getPrice());
            //品牌名称
            carVo.setProductBrand(product.getBrandName());
            //商品sn码
            carVo.setProductSn(product.getProductSn());
            //商品图片
            carVo.setProductPic(product.getPic());
            //类型编号id
            carVo.setProductCategoryId(product.getProductCategoryId());
            //sku表主键id
            carVo.setProductSkuId(skuStock.getId());
            //skucode码
            carVo.setProductSkuCode(skuStock.getSkuCode());
            //商品名称
            carVo.setProductName(product.getName());
            //商品标题
            carVo.setProductSubTitle(product.getSubTitle());
            //sku
            carVo.setProductAttr(skuStock.getSpData());
            //删除状态字段
            carVo.setDeleteStatus(car.getDeleteStatus());
            //添加时间
            carVo.setCreateDate(car.getCreateDate());
            //购物车商品数量
            carVo.setQuantity(car.getQuantity());
            //给新的集合赋值
            listVo.add(carVo);
        }
        return listVo;
    }

    private List<CarVo> getlist(Integer[] cartIds) {
        //查询商品信息
        //先查询相关联的表数据
        //先查询出购物车表的数据
        List<Car> list=mapper.findlist(cartIds);
        ArrayList<CarVo> listVo = new ArrayList<>();
        //循环list集合Po转Vo->前台
        //TODO 测试数据，后续可迭代为MyBatis动态查询
        for (Car car : list) {
            //先查询相关联的表数据
            //查询product商品表的关联数据
            Product product=cProductMapper.findByCar(car.getProductId());
            //查询sku表的关联数据
            SkuStockList skuStock=cReadHistoryMapper.findByCar(car.getProductSkuId());
            //new一个carVo对象用于赋值
            CarVo carVo = new CarVo();
            //主键id
            carVo.setId(car.getId());
            //用户id
            carVo.setMemberId(car.getMemberId());
            //用户名称
            carVo.setMemberNickname(car.getMemberNickname());
            //商品表主键id
            carVo.setProductId(car.getProductId());
            //价格
            carVo.setPrice(skuStock.getPrice());
            //品牌名称
            carVo.setProductBrand(product.getBrandName());
            //商品sn码
            carVo.setProductSn(product.getProductSn());
            //商品图片
            carVo.setProductPic(product.getPic());
            //类型编号id
            carVo.setProductCategoryId(product.getProductCategoryId());
            //sku表主键id
            carVo.setProductSkuId(skuStock.getId());
            //skucode码
            carVo.setProductSkuCode(skuStock.getSkuCode());
            //商品名称
            carVo.setProductName(product.getName());
            //商品标题
            carVo.setProductSubTitle(product.getSubTitle());
            //sku
            carVo.setProductAttr(skuStock.getSpData());
            //删除状态字段
            carVo.setDeleteStatus(car.getDeleteStatus());
            //添加时间
            carVo.setCreateDate(car.getCreateDate());
            //购物车商品数量
            carVo.setQuantity(car.getQuantity());
            //给新的集合赋值
            listVo.add(carVo);
        }
        return listVo;
    }
}
